/*********************************************************************
 * Author : Amogh Chakravarthy
 *********************************************************************/

package bbd.crawler.dao.ibatis;

import bbd.crawler.util.Console;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.Reader;
import java.util.ResourceBundle;

/**
 * Factory class to get an instance of the iBATIS SQL Map object
 */
public class SQLMapFactory {

    private static final String BUNDLE_BASE_NAME       = "crawler";
    private static final String BUNDLE_KEY_SQLMAP_PATH = "sqlmap.xml.with.path";

    private static SqlMapClient sqlMapClient = null;
    
    //--------------------------------------------------------------------------
    /**
     * Return the instance of the SQL Map Client to the caller.
     * This class implements the singleton design pattern.
     */
    public static SqlMapClient getClientInstance () throws Exception {
    
        if ( sqlMapClient == null ) {

            String sqlMapConfigXML =
                            ResourceBundle.getBundle (
                                                BUNDLE_BASE_NAME
                                             ).getString (
                                                    BUNDLE_KEY_SQLMAP_PATH
                                               );

            if ( sqlMapConfigXML != null ) {

                try {

                    Reader xmlReader = Resources.getResourceAsReader ( sqlMapConfigXML );

                    sqlMapClient = SqlMapClientBuilder.buildSqlMapClient ( xmlReader );
                }
                catch ( Exception ex ) {

                    Console.error ( 
                                "SQLMapFactory.getClientInstance",
                                "(EXCEPTION) Stack Trace ..."
                             );

                    ex.printStackTrace();

                    sqlMapClient = null;

                    throw ex;
                }
            }
        }
        
        return sqlMapClient;
        
    } // end function getClientInstance

} // end class SQLMapFactory
